package com.moneyhelper.message.email;

import com.moneyhelper.message.model.MailMessageModel;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import javax.mail.internet.MimeMessage;
import java.util.Map;

/**
 * @Author yanggld
 * @Date 2019/7/10-14:16
 * @Description
 */
@Slf4j
@Service
public class EmailService {

	@Autowired
	private JavaMailSender mailSender;

	public boolean sendHtmlEmail(FreeMarkerConfigurer freeMarkerConfigurer,MailMessageModel mailMessageModel){
		MimeMessage message=mailSender.createMimeMessage();
		try {
			//true表示需要创建一个multipart message
			MimeMessageHelper helper=new MimeMessageHelper(message,true);
			helper.setFrom(mailMessageModel.getFrom());
			helper.setTo(mailMessageModel.getToEmail());
			helper.setSubject(mailMessageModel.getSubject());
			//true代表支持html
			helper.setText(getContentByTemplateName(freeMarkerConfigurer,mailMessageModel.getTemplateName(),mailMessageModel.getParams()),true);
			mailSender.send(message);
			log.info("html格式邮件发送成功");
		}catch (Exception e){
			log.info("html格式邮件发送失败:{}",e.getMessage());
			return false;
		}
		return true;
	}


	private String getContentByTemplateName(FreeMarkerConfigurer freeMarkerConfigurer,String templateName, Map<String, Object> params) throws Exception {
		Template template = freeMarkerConfigurer.getConfiguration().getTemplate(templateName);
		//解析模板并替换动态数据，最终code将替换模板文件中的${code}标签。
		return FreeMarkerTemplateUtils.processTemplateIntoString(template, params);
	}
}
